package com.zh.work.aop.fc;

import com.alibaba.fastjson.JSON;
import io.swagger.annotations.ApiOperation;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import com.zh.common.entity.JSONResult;
import java.lang.reflect.Method;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;

/**
 * code is far away from bug with the animal protecting
 * ┏┓　　　┏┓
 * ┏┛┻━━━┛┻┓
 * ┃　　　　　　　┃
 * ┃　　　━　　　┃
 * ┃　┳┛　┗┳　┃
 * ┃　　　　　　　┃
 * ┃　　　┻　　　┃
 * ┃　　　　　　　┃
 * ┗━┓　　　┏━┛
 * 　　┃　　　┃神兽保佑
 * 　　┃　　　┃代码无BUG！
 * 　　┃　　　┗━━━┓
 * 　　┃　　　　　　　┣┓
 * 　　┃　　　　　　　┏┛
 * 　　┗┓┓┏━┳┓┏┛
 * 　　　┃┫┫　┃┫┫
 * 　　　┗┻┛　┗┻┛
 *
 * @Description: 调用付聪科技接口，记录操作过程值
 * @Author: Liard
 * @Create in: 2020/7/17 14:15
 * @Version: 1.0.1
 */
@Aspect
@Component
public class FcAop {
    private static final Logger log = LoggerFactory.getLogger(FcAop.class);

    @Pointcut(value = "execution(* com.zh.work.controller.out.fc.FcController.*(..))")
    public void verifyApiReq() { }

    @Autowired
    private MongoTemplate mongoTemplate;

    @Async
    @AfterReturning(value = "verifyApiReq()", returning = "result")
    public void aroundApiAop(JoinPoint jp, JSONResult result) {
        Map<String, String> map = new LinkedHashMap<>();
        StringBuffer sb = new StringBuffer();
        // 记录请求值
        MethodSignature methodSignature = (MethodSignature) jp.getSignature();
        Method method = methodSignature.getMethod();
        ApiOperation apiOperation = method.getAnnotation(ApiOperation.class);
        map.put("_id", UUID.randomUUID().toString());
        map.put("method", method.getName());
        log.info("###### 调用付聪验证接口 -> {}", method.getName());
        sb.append("name:")
                .append(jp.getArgs()[0])
                .append(",phone:")
                .append(jp.getArgs()[1])
                .append(",certNo:")
                .append(jp.getArgs()[2]);
        map.put("param", sb.toString());
        map.put("notes", apiOperation.notes());
        map.put("result", result.toString());
        mongoTemplate.save(map, "fc_api");
    }
}
